package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 超时订单 自动取消   每分钟处理一次
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void orderTimeOut() {
        log.info("定时处理超时订单:{}",LocalDateTime.now());
//        先查到 超时的订单
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, localDateTime);
        if(byStatusAndOrderTime!=null && byStatusAndOrderTime.size()>0) {
            byStatusAndOrderTime.forEach(byStatusAndOrderTime1-> {
                byStatusAndOrderTime1.setCancelTime(LocalDateTime.now());
                byStatusAndOrderTime1.setCancelReason("超时自动取消");
                byStatusAndOrderTime1.setStatus(Orders.CANCELLED);
                orderMapper.update(byStatusAndOrderTime1);
            });
        }
    }

    /**
     * 每天凌晨一点自动去处理前一天的 派送中的订单 ，修改为 已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void  orderPaiSongOut() {
        log.info("派送订单处理{}",LocalDateTime.now());
        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if(byStatusAndOrderTime!=null && byStatusAndOrderTime.size()>0) {
            byStatusAndOrderTime.forEach(byStatusAndOrderTime1-> {
                byStatusAndOrderTime1.setStatus(Orders.COMPLETED);
                orderMapper.update(byStatusAndOrderTime1);
            });
        }
    }
}
